package com.touzbi.hss.bo;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;

import com.touzbi.hss.beans.Patient;
import com.touzbi.hss.dao.AbstractPatientDAO;
import com.touzbi.hss.dao.PatientDAO;
import com.touzbi.hss.validator.AbstractValidator;
import com.touzbi.hss.validator.Validator;
import com.touzbi.hss.validator.ValidatorException;

public class FormBO {

	private static final String FIRST_NAME_PARAM = "firstName";
	private static final String LAST_NAME_PARAM = "lastName";
	private static final String MAIL_PARAM = "mail";
	private static final String PHONE_NUMBER_PARAM = "phoneNumber";
	private AbstractPatientDAO patientDAO;
	private Map<String, String> error = new HashMap<String, String>();

	public FormBO(Session session) {
		this.patientDAO = new PatientDAO(session);
	}

	public Patient getPatient(HttpServletRequest req) {
		Patient patient = new Patient();
		AbstractValidator validator = new Validator();
		try {
			patient.setFirstName(validator.getValidFirstName(getParamValue(req,
					FIRST_NAME_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(FIRST_NAME_PARAM, e.getMessage());
		}
		try {
			patient.setLastName(validator.getValidLastName(getParamValue(req,
					LAST_NAME_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(LAST_NAME_PARAM, e.getMessage());
		}
		try {
			patient.setMail(validator.getValidMail(getParamValue(req,
					MAIL_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(MAIL_PARAM, e.getMessage());
		}
		try {
			patient.setPhoneNumber(validator.getValidPhoneNumber(getParamValue(
					req, PHONE_NUMBER_PARAM)));
		} catch (ValidatorException e) {
			this.error.put(PHONE_NUMBER_PARAM, e.getMessage());
		}
		return patient;
	}

	private String getParamValue(HttpServletRequest req, String paramName) {
		String param = req.getParameter(paramName);
		return param;
	}

	public Patient addPatient(HttpServletRequest req) {
		Patient patient = getPatient(req);
		if (this.error.isEmpty()) {
			this.patientDAO.addPatient(patient);
		}
		return patient;
	}

	public Map<String, String> getError() {
		return this.error;
	}
}
